/*
**  Copyright (C), CHENGDU GONGWEI TECHNOLOGY CO.,LTD.
**
**  Project:	Manager Unit v1.0
**  File:    	
**  Author: 	zhaozhuyu
**  Date:    	2017/05/20
**
**  Purpose:
**    		.
**
**  History: 
**  <author>   <time>          <version >   <desc>
*	$$Author$$
*/


/* Include files. */

extern "C" { 
	#include "standard.h"
	#include "util.h"
	#include "debug.h"
} 
#include "network.h"
#include "netcli.h"
#include "subsystemcore.h"

/* Local function declarations. */

/* Macro API definitions. */

/* Global variable declarations. */

/* Type definitions. */

/* Local function definitions. */

netCli::netCli(u32 ip, u16 port, u32 fd)
		:netObject(ip, port, fd) 
{
	_agent_name = string("access");	
}

int netCli::bind()
{
	int ret;
	
	if (subSystem::bindSubSystem(_agent_name, this)) {
		DEBUG("new connection " NIPQUAD_FMT ":%d , netobj = %p, socket = %d, id = %u\n",
		 NIPQUAD(_ip), _port, this, _fd, _id);
		ret = 1;
	}
	else {
		ERROR("%s service don't start!\n", _agent_name.c_str());
		ERROR("bind faild, " NIPQUAD_FMT ":%d , netobj = %p, socket = %d, id = %u\n",
		  NIPQUAD(_ip), _port, this, _fd, _id);
		ret = 0;
	}

	return ret;
}

#define READ_BUFF (1024 * 4)
int netCli::recvMsg()
{
	char buff[READ_BUFF];
	int ret;
	buff[0] = '\0';
	ret = netRecv(_fd, (u8*)buff, READ_BUFF);
	if (ret < 0) {
		return e_ERROR;
	}
	else if (ret == 0){
		return e_CONTINUE;
	}
	else if (ret == READ_BUFF){
		WARN("error, buff >= %d\n", READ_BUFF);
		return e_ERROR;
	}
	else {
		buff[ret] = '\0';
		sendSubSystem(_sub->_L, "netcli", _sub->_name.c_str(), 
			"cli", buff, _id);
		return e_OK;
	}

}

int netCli::sendMsg()
{
	string s = _out_queue.front();
	_out_queue.pop();
	int n = netSend(_fd, (u8 *)s.c_str(), s.size());
	if (n >= 0) {
		return e_OK;
	}
	else {
		WARN("send data failed, %s\n", strerror(errno));
		return e_ERROR;
	}	
}


